package stack.hard;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * 基本计算器
 * 示例 1：
 *
 * 输入：s = "1 + 1"
 * 输出：2
 * 示例 2：
 *
 * 输入：s = " 2-1 + 2 "
 * 输出：3
 * 示例 3：
 *
 * 输入：s = "(1+(4+5+2)-3)+(6+8)"
 * 输出：23
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/basic-calculator
 */
public class BasicCalculator_224 {

    public int calculate(String s) {

        Stack<Integer> integerStack = new Stack<>();
        int res = 0, num = 0,sign = 1;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                int j = i;
                //(123 + 123)
                while(j < s.length() && (Character.isDigit(s.charAt(j)))) {
                    num = num * 10 + (s.charAt(j) - '0');
                    j++;
                }
                i = j - 1;
                res += (num * sign);
                num = 0;
            } else if (c == '(') {
                // ( 123 + (123 + 123))
                integerStack.push(res);
                integerStack.push(sign);
                res = 0;
                sign = 1;
            } else if (c == ')') {
                res += sign * num;
                num = 0;
                res *= integerStack.pop();
                res += integerStack.pop();

            } else if (c == '+') {
                sign = 1;
            } else if (c == '-') {
                sign = -1;
            } else {
                continue;
            }
        }
        return res;
    }



    public static void main(String[] args) {
        BasicCalculator_224 bc = new BasicCalculator_224();
    }

}
